package cn.com.headfree.util;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 * @Title  DateUtils.java
 * @Package cn.com.headfree.base.utils
 * @Description 时间工具类
 * @author yangwang
 * @date  2020年3月13日 下午3:20:10
 */
@Component
public class DateUtils {
	private static final Logger LOG = LogManager.getLogger(DateUtils.class);

	/**
	 * 时间格式数组
	 * @author yangwang
	 *  */
	private static String[] datePatterns ={
			"yyyy-MM-dd",
			"yyyy-MM-dd HH",
			"yyyy-MM-dd HH:mm",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy/MM/dd",
            "yyyy/MM/dd HH",
            "yyyy/MM/dd HH/mm",
            "yyyy/MM/dd HH/mm/ss",
            "yyyyMMdd",
            "yyyyMMddHH",
            "yyyyMMddHHmm",
            "yyyyMMddHHmmss",
            "yyyy MM dd",
            "yyyy MM dd HH",
            "yyyy MM dd HH mm",
            "yyyy MM dd HH mm ss",
            "yyyy年MM月dd日",
            "yyyy年MM月dd日HH时",
            "yyyy年MM月dd日HH时mm分",
            "yyyy年MM月dd日HH时mm分ss秒"
	};

	/**
	 * 转换时间字符串为时间
	 * @author yangwang
     * @param dateStr 时间字符串
     * @return 解析出来的日期，如果没有匹配的返回null
     */
    public static Date parseDateStrToDate(String dateStr){
        try {
			SimpleDateFormat sdf = new SimpleDateFormat();
			Date date =null;
			for(String pattern:datePatterns){
				sdf.applyPattern(pattern);
			    //设置解析日期格式是否严格解析日期
				sdf.setLenient(false);
			    ParsePosition pos = new ParsePosition(0);
			    date = sdf.parse(dateStr, pos);
			    if(date!=null){
			        return date;
			    }
			}
		} catch (Exception e) {
			LOG.error("转换时间字符串为时间异常"+e);
		}
        return null;
    }


	/**
	 * 获取时间的当天开始时间
	 * @author yangwang
	 * @param date
	 * @param Date
	 *  */
	public static Date getStartTimeOfDay(Date date){
		try {
			if(null != date) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(date);
				cal.set(Calendar.HOUR_OF_DAY, 0);
				cal.set(Calendar.MINUTE, 0);
				cal.set(Calendar.SECOND, 0);
				cal.set(Calendar.MILLISECOND, 0);
				return cal.getTime();
			}
		} catch (Exception e) {
			LOG.error("获取时间的当天开始时间异常"+e);
		}
		return null;
	}

	/**
	 * 获取时间的当天结束时间
	 * @author yangwang
	 * @param date
	 * @param Date
	 *  */
	public static Date getEndTimeOfDay(Date date){
		try {
			if(null != date) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(date);
				cal.set(Calendar.HOUR_OF_DAY, 23);
				cal.set(Calendar.MINUTE, 59);
				cal.set(Calendar.SECOND, 59);
				cal.set(Calendar.MILLISECOND, 999);
				return cal.getTime();
			}
		} catch (Exception e) {
			LOG.error("获取时间的当天结束时间"+e);
		}
		return null;
	}

}
